﻿//using MiniSoftware;
using apitest.Application.Entities.Pms;
using MiniExcelLibs;
using MiniSoftware;
using Newtonsoft.Json;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using Document = Spire.Doc.Document;

namespace apitest.Application.Test.Services
{
    [DynamicApiController]
    public class WordTestService 
    {
        ISqlSugarClient _db;
        public WordTestService(ISqlSugarClient db)
        {
            _db = db;
        }
        public async Task T1()
        {
            var path = "./111.docx";
            var templatePath = "./222.docx";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            var value = new
            {
                name = "张三四",
                LoopData = new List<object>()
         {
             new {
                 Type="类型A",
                 users=new List<object>(){new {name="83"}},
                 Items = new List<object>() {new {Name = "A-1"}, new {Name = "A-2"},}
             },
             new
             {
                 Type="类型B",
                  users=new List<object>(){new {name="223"}},
                 Items = new List<object>() {new {Name = "B-1"}, new {Name = "B-2"}, new {Name = "B-3"},}
             },
         }
            };

            var value1 = new Dictionary<string, object>()
            {
                ["name"] = "王五",
                ["list"] = new List<Dictionary<string, object>>()
                {
                    new Dictionary<string, object>()
                    {
                        ["name"]="aaa",
                        ["age"]=111,
                        ["users"]=new List<object>()
                        {
                          new  {
                          身份="aa",
                          bb="bb"

                          }
                        }
                    },
                     new Dictionary<string, object>()
                    {
                        ["name"]="bbb",
                        ["age"]=222,
                          ["users"]=new List<object>()
                        {
                          new  {
                          身份="cc",
                          bb="dd"
                          },
                           new  {
                          身份="1123333333",
                          bb="222222222"
                          },
                             new  {
                          身份="321333",
                          bb="4444444444"
                          }
                        }
                    }
                }
            };

            MiniWord.SaveAsByTemplate(path, templatePath, value1);
        }

        public async Task T2()
        {
            var path = "./222.docx";
            var templatePath = "./stability.docx";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            //载入文档
            Document document = new Document(templatePath);
            //获取第一个节
            Section section = document.Sections[0];

            ////获取第一个表格
            Table table = section.Tables[0] as Table;
            ////给表格应用内置样式
            table.ApplyStyle(Spire.Doc.Documents.DefaultTableStyle.LightGridAccent3);

            section.AddTable();
            Table table1 = section.Tables[1] as Table;
            table1.ApplyStyle(Spire.Doc.Documents.DefaultTableStyle.LightGrid);
            table1.AddCaption("name", CaptionNumberingFormat.Number, CaptionPosition.AboveItem);


            var cell = table1.AddRow().AddCell();
            var par = cell.AddParagraph();
            par.AppendField("{{name}}}", FieldType.FieldEmpty);
            //cell.InsertXHTML("afdsafds");
            cell = table1.AddRow().AddCell();
            cell.InsertXHTML("{{name}}");
            //保存文档
            document.SaveToFile(path);
        }

       

        public async Task<dynamic> T4(int Id=6)
        {
            var templatePath = "./stability.docx";
            var path = "./aaa.docx";
            var resultPath = "./bbb.docx";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            if (File.Exists(resultPath))
            {
                File.Delete(resultPath);
            }
            var allList = await _db.Queryable<QC_Stability_Record>()
                .LeftJoin<QC_Stability>((t1, t2) => t1.StabilityId == t2.Id)
                .Where((t1, t2) => t1.StabilityId == Id)
                .Select((t1, t2) => new
                {
                    t1,
                    t2
                }).ToListAsync();

            var tableColumn = JsonConvert.DeserializeObject<List<string>>(allList.FirstOrDefault().t2.ResultTemplate);
            Document doc = new Document(templatePath);
            var text = new TextRange(doc);
            //创建表格
            var section = doc.Sections[0];
            var table = section.Tables[0] as Table;
            table.ResetCells(2, tableColumn.Count + 2);
            table.DefaultRowHeight = 20;
            table.ApplyStyle(DefaultTableStyle.TableGrid);
            //表头
            TableRow tbRow = table.Rows[0];
            tbRow.IsHeader = true;
            text = tbRow.Cells[0].AddParagraph().AppendText("取样点 Sampling point");
            text.CharacterFormat.FontSize = 8;
            text.CharacterFormat.Bold = true;
            text = tbRow.Cells[1].AddParagraph().AppendText("检测日期 Test date ");
            text.CharacterFormat.FontSize = 8;
            text.CharacterFormat.Bold = true;


            for (int i = 0; i < tableColumn.Count; i++)
            {
                text = tbRow.Cells[i + 2].AddParagraph().AppendText($"{tableColumn[i]}");
                text.CharacterFormat.FontSize = 8;
                text.CharacterFormat.Bold = true;
            }

            //表体
            tbRow = table.Rows[1];
            text = tbRow.Cells[0].AddParagraph().AppendText("{{Point}}");
            text.CharacterFormat.FontSize = 8;
            text = tbRow.Cells[1].AddParagraph().AppendText("{{PlanTime}}");
            text.CharacterFormat.FontSize = 8;
            for (int i = 0; i < tableColumn.Count; i++)
            {
                text = tbRow.Cells[i + 2].AddParagraph().AppendText($"{{{{{tableColumn[i]}}}}}");
                text.CharacterFormat.FontSize = 8;
            }

            //组织数据
            var conditionList = allList.GroupBy(o => o.t1.ConditionRemark).Select(o => o.Key).ToList();

            var dataList = new List<dynamic>();
            foreach (var con in conditionList)
            {
                var list = allList.Where(o => o.t1.ConditionRemark == con).ToList();
                dataList.Add(new Dictionary<string, object>()
                {
                    ["Cat"] = list[0].t2.CAT,
                    ["Batch"] = list[0].t2.Batch,
                    ["ConditionRemark"] = con,
                });

            }
            var res = new
            {
                List = dataList,
            };
            doc.SaveToFile(path);
            Thread.Sleep(1000);
            MiniWord.SaveAsByTemplate(resultPath, path, res);
            return res;
        }

        public async Task<dynamic> T5()
        {
            var path = "./bbb.docx";
            var templatePath = "./aaa.docx";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            var value = new
            {

                List = new List<object>()
         {
             new {
                 Cat="类型A",
                 Batch="Batch1111",
                 Items = new List<object>() {new {Name = "A-1"}, new {Name = "A-2"},}
             },
             new
             {
                 Cat="类型B",
                  Batch="Batch222",
                 Items = new List<object>() {new {Name = "B-1"}, new {Name = "B-2"}, new {Name = "B-3"},}
             },
         }
            };
            MiniWord.SaveAsByTemplate(path, templatePath, value);
            return "";
        }

        public async Task<dynamic> T6()
        {
            var path = "./123.docx";
            Document doc = new Document(path);
            var a = doc.Sections[0].ChildObjects[4].FirstChild;
            var b = doc.Sections[0].Tables[0].LastCell.FirstParagraph.Text;
            //创建StringBuilder实例
            StringBuilder sb = new StringBuilder();

            //遍历文档中所有节
            foreach (Section section in doc.Sections)
            {
                //遍历每一节中的段落
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    //获取段落文本并保存到StringBuilder实例中
                    sb.AppendLine(paragraph.Text);
                }
            }

            var tb = doc.Sections[0].Tables[0];
            sb = new StringBuilder();
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                TableRow row = tb.Rows[i];
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    TableCell cell = row.Cells[j];
                    for (int r = 0; r < cell.Paragraphs.Count; r++)
                    {
                        sb.AppendLine(cell.Paragraphs[r].Text);
                    }
                }
            }
            return sb.ToString();
            return doc.GetText().Replace("\t", "").Replace("\r", "").Replace("\n", "");
        }

        [HttpPost]
        public async Task<dynamic> T7(IFormFile file)
        {

            var templatePath = "./HPLC.docx";
            var path = "./test.docx";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            Stream stream = file.OpenReadStream();
            var list = MiniExcel.Query(stream).ToList();
            return list;
            //var list = MiniExcel.Query("./123.xlsx").ToList();
            var res = new Dictionary<string, object>();
            res.Add("txt1", list[12].M);
            res.Add("txt2", list[22].M);
            res.Add("txt3", list[133].M);
            res.Add("txt4", list[52].N);
            res.Add("txt5", list[53].N);
            res.Add("txt6", list[42].M);
            res.Add("txt7", list[96].M);
            res.Add("txt8", list[79].M);

            MiniWord.SaveAsByTemplate(path, templatePath, res);

            byte[] fileBytes = File.ReadAllBytes(path);
            var ms = new MemoryStream(fileBytes);
            ms.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "导出结果.docx"
            };

        }

        [HttpPost]
        public async Task<dynamic> T8(IFormFile file)
        {
            var filePath = "";
            filePath = "./HPLC-11073-A 2025-0115-0159-18336.xlsx";
            filePath = "./HPLC-11807-A 2024-0530-0918-56147.xlsx";
            var templatePath = "./HPLC.docx";
            var path = "./test.docx";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            var list = new List<dynamic>();
            if (file != null)
            {
                Stream stream = file.OpenReadStream();
                list = MiniExcel.Query(stream).ToList();
            }
            else
            {
                list = MiniExcel.Query(filePath).ToList();
            }

            var res = JsonConvert.DeserializeObject<List<result_class>>(JsonConvert.SerializeObject(list));
            var data = new Dictionary<string, object>();
            var txt = res.FirstOrDefault(o => o.H == "说明:")?.M;
            if (txt != null)
            {
                var arr=txt.Split('\n').ToList();
                if (arr.Count>1)
                {
                    data.Add("txt1_1", arr.FirstOrDefault(o=>o.StartsWith("色谱柱"))?.Replace("色谱柱","").Replace("：","").Replace(":",""));
                    data.Add("txt1_2", arr.FirstOrDefault(o=>o.StartsWith("稀释剂"))?.Replace("稀释剂", "").Replace("：","").Replace(":",""));
                    data.Add("txt1_3", arr.FirstOrDefault(o=>o.StartsWith("浓度"))?.Replace("浓度", "").Replace("：","").Replace(":",""));
                }
                else
                {
                    data.Add("txt1_1", txt);
                }
            }
            data.Add("txt2", res.FirstOrDefault(o => o.H == "温度:")?.M);
            data.Add("txt3", res.FirstOrDefault(o => o.H == "信号波长:")?.M);
            data.Add("txt4", res.FirstOrDefault(o => o.J == "A")?.O);
            data.Add("txt5", res.FirstOrDefault(o => o.J == "B")?.O);
            data.Add("txt6", res.FirstOrDefault(o => o.H == "流量:")?.M);
            data.Add("txt7", res.FirstOrDefault(o => o.H == "进样量:")?.M);
            data.Add("txt8", res.FirstOrDefault(o => o.H == "停止时间:")?.M);

            //时间表
            var firstRow = res.FirstOrDefault(o => o.F == "Row ID" && o.R == "百分比 (%)" && o.O == "已使用");
            //第一行
            if (firstRow != null)
            {
                var index = res.IndexOf(firstRow);
                data.Add("txt10_1", "0.0");
                data.Add("txt10_2", res[index + 1].R);
                data.Add("txt10_3", res[index + 2].R);
            }
            //其余行
            firstRow = res.FirstOrDefault(o => o.F == "时间表");
            if (firstRow != null)
            {
                var index = res.IndexOf(firstRow);
                int i = 1;
                var flag = true;
                while (flag)
                {
                    var row = res[index + i + 2];
                    double rowId = 0;
                    double.TryParse(row.F, out rowId);
                    if (rowId != i)
                    {
                        flag = false;
                    }
                    else
                    {
                        data.Add($"txt1{i}_1", row.J);
                        data.Add($"txt1{i}_2", row.N);
                        data.Add($"txt1{i}_3", row.O);
                        i++;
                    }
                }
            }

            MiniWord.SaveAsByTemplate(path, templatePath, data);
            byte[] fileBytes = File.ReadAllBytes(path);
            var ms = new MemoryStream(fileBytes);
            ms.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                FileDownloadName = "导出结果.docx"
            };
        }

        public async Task<dynamic> T9()
        {
            var templatePath = "./HPLC.docx";
            Document doc = new Document(templatePath);
            for (int i = 0; i < doc.PageCount; i++)
            {
                Image image = doc.SaveToImages(i, ImageType.Bitmap);
                image.Save($"./Sample{i}.png", ImageFormat.Png);
            }
            return "";
        }

        public async Task<dynamic> T10()
        {
        
            List<Image> imageList = new List<Image>();
            imageList.Add(Image.FromFile($"./Sample0.png"));
            imageList.Add(Image.FromFile($"./Sample1.png"));
            imageList.Add(Image.FromFile($"./Sample2.png"));

            //纵向拼接
            int height = 0;
            //计算总长度
            foreach (Image i in imageList)
            {
                height += i.Height;
            }
            //宽度不变
            int width = imageList.Max(x => x.Width);
            //构造最终的图片白板
            Bitmap tableChartImage = new Bitmap(width, height);
            Graphics graph = Graphics.FromImage(tableChartImage);
            //初始化这个大图
            graph.DrawImage(tableChartImage, width, height);
            //初始化当前宽
            int currentHeight = 0;
            foreach (Image i in imageList)
            {
                //拼图
                graph.DrawImage(i, 0, currentHeight);
                //拼接改图后，当前宽度
                currentHeight += i.Height;
            }
            tableChartImage.Save("./111.png");
            return "";
        }

        public async Task<dynamic> T11()
        {
            var path = "./stp/sop.doc";
            Document doc = new Document(path);
            var Sections = doc.Sections;
            foreach ( Section section  in Sections) { 
                var Paragraphs = section.Paragraphs ;
                foreach (Paragraph pra in Paragraphs)
                {
                    
                    Console.WriteLine( pra.Text);
                }
            }
            doc.SaveToFile("./stp/stp.html");
            return doc.GetText();
        }
        public class enum_class
        {
            public int value { get; set; }
            public string label { get; set; }
            public object ext { get; set; }
        }

        public class result_class
        {
            public string A { get; set; }
            public string B { get; set; }
            public string C { get; set; }
            public string D { get; set; }
            public string E { get; set; }
            public string F { get; set; }
            public string G { get; set; }
            public string H { get; set; }
            public string I { get; set; }
            public string J { get; set; }
            public string K { get; set; }
            public string L { get; set; }
            public string M { get; set; }
            public string N { get; set; }
            public string O { get; set; }
            public string P { get; set; }
            public string Q { get; set; }
            public string R { get; set; }
            public string S { get; set; }
            public string T { get; set; }
            public string U { get; set; }
            public string V { get; set; }
            public string W { get; set; }
            public string X { get; set; }
            public string Y { get; set; }
            public string Z { get; set; }

        }

    }
}
